package org.springmole.web.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller("springMoleFileController")
public class FileController {

	private final static Map<String, String> CONTENT_TYPE_MAP = new HashMap<String, String>();
	
	private final static String RESOURCE_PATH = "/org/springmole/resource/";
	
	static {
		CONTENT_TYPE_MAP.put(".js", "text/javascript");
		CONTENT_TYPE_MAP.put(".css", "text/css");
		CONTENT_TYPE_MAP.put(".xml", "text/xml");
		CONTENT_TYPE_MAP.put(".xslt", "text/xml");
	}
	
	
	@RequestMapping(value="/file.spy", method=RequestMethod.GET)
		public void processFileGet(
			@RequestParam(required=true, value="filename") String fileName,
			OutputStream outputStream,
			HttpServletResponse response) throws IOException {
		
		String extension = fileName.substring(fileName.lastIndexOf("."));
		
		System.out.println("fileName=" + fileName);
		System.out.println("fileName=" + extension);
		
		response.setContentType(CONTENT_TYPE_MAP.get(extension));
						
		copyFile(RESOURCE_PATH + fileName, outputStream);
	}
	
	
	
	private void copyFile(String fileName, OutputStream outputStream) throws IOException {
		InputStream inputStream = this.getClass().getResourceAsStream(fileName);
		if (inputStream != null) {
			InputStream in = new BufferedInputStream(inputStream);
	 		OutputStream out = new BufferedOutputStream(outputStream);
			while (true) {
			   int data = in.read();
			   if (data == -1) {
			      break;
			   }
			   out.write(data);
			}
			out.flush();			
		} else {
			// TODO page not found
			System.out.println("page not found");
		}
	}
	
		
}
